package fieldmaps.files;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

import fieldmaps.database.DatabaseVoronoiMap;
import fieldmaps.types.VoronoiMapInfo;

public class SaveVoronoiMapToFile implements ISaveMapToFile {
	private static Logger LOGGER = Logger.getLogger(SaveVoronoiMapToFile.class);

	private String mapName;
	private String outputFile;
	private DatabaseVoronoiMap dbMap;
	
	public SaveVoronoiMapToFile(String mapName, String outputFile) {
		if (mapName == null || outputFile == null || mapName.isEmpty() || outputFile.isEmpty()) {
			throw new IllegalArgumentException();
		}
		this.mapName = mapName.trim();
		this.outputFile = outputFile.trim();
	}

	public void saveMap() throws IOException {
		this.dbMap = DatabaseVoronoiMap.loadMap(mapName);
		VoronoiMapInfo header = this.dbMap.getMapInfo();
		saveHeader (header, this.outputFile + ".hdr");
		saveData (this.outputFile + ".voronoi");
		LOGGER.info("Map successfully saved!");
	}

	private void saveData(String fileName) throws IOException {
		//TODO: Grabar corectamente
//		FileOutputStream file = new FileOutputStream(fileName);
//		VoronoiMapInfo mapInfo = dbMap.getMapInfo();
//		Integer value;
//
//		this.dbMap.startCellIteration();
//		Coordinate coordinate = new Coordinate(mapInfo.getUlxmap(), mapInfo.getUlymap());
//		try {
//			for (int i = 0; i < mapInfo.getNrows(); i++) {
//				for (int j = 0; j < mapInfo.getNcols(); j++) {
//					Object userData = (this.dbMap.getCell(coordinate).get(0).getUserData());
//					if (userData == null) {
//						value = mapInfo.getNodata();
//					} else {
//						value = (Integer) userData;
//					}
//					int c = 0;
//					for (int k = bytes.length-1; k >= 0; k--) {
//						bytes[c++] = (byte)(value & 0x000000FF);
//						value >>= k * 8;
//					}
//					file.write(bytes);
//					file.flush();
//					coordinate.x += mapInfo.getXdim();
//				}
//				coordinate.x = mapInfo.getUlxmap();
//				coordinate.y += mapInfo.getUlymap();
//			}
//		} catch (NoSuchElementException e) {
//
//		}
//		this.dbMap.resetCellIteration();

//		file.flush();
//		file.close();
	}
	
	private void saveHeader(VoronoiMapInfo header, String file) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(new File(file)));
		
		bw.write("xUpperLeft\t" + header.getxUpperLeft() + "\n");
		bw.write("yUpperLeft\t" + header.getyUpperLeft() + "\n");
		bw.write("xLowerRight\t" + header.getxLowerRight() + "\n");
		bw.write("yLowerRight\t" + header.getyLowerRight() + "\n");

		bw.close();
	}
}
